# -*- coding: utf-8 -*-
# @Time : 2022/7/24 10:10
# @Author : WangYunfei
# @FileName: 翻译.py
# @Email: lxb_wyf@163.com
"""
网易有道翻译
"""
import hashlib
import random
import time

import requests


class YD(object):

    def __init__(self):
        self.url = "https://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule"
        self.headers = {
            'Referer': 'http://fanyi.youdao.com/',
            "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36"
        }
        self.cookies = {
            "OUTFOX_SEARCH_USER_ID": "1008314158@10.110.96.153",
            # "OUTFOX_SEARCH_USER_ID_NCOO": "1935111395.6125293",
            # "fanyi-ad-id": "308216",
            # "fanyi-ad-closed": "0",
            # "___rl__test__cookies": "1658627339479"
        }

    def js(self, key):
        """
        获取 js 加密的 sign参数
        :param key: 翻译的文本内容
        :return:
        """
        t = self.md5(self.headers["user-agent"])
        r = "" + str(int(time.time() * 1000))
        i = r + str(random.randint(1, 9))
        return {
            "ts": r,
            "bv": t,
            "salt": i,
            "sign": self.md5("fanyideskweb" + key + i + "Ygy_4c=r#e#4EX^NUGUc5")
        }

    @staticmethod
    def md5(value):
        md = hashlib.md5()
        md.update(value.encode('utf8'))  # 接收字节类型  16进制表示
        return md.hexdigest()

    def spider(self, key):
        r = self.js(key)
        i = len(key)
        _data = {
            "i": key,
            "from": "AUTO",
            "to": "AUTO",
            "smartresult": "dict",
            "client": "fanyideskweb",
            "salt": r["salt"],
            "sign": r["sign"],
            "lts": r["ts"],
            "bv": r["bv"],
            "doctype": "json",
            "version": "2.1",
            "keyfrom": "fanyi.web",
            "action": "FY_BY_CLICKBUTTION"
        }
        try:
            res = requests.post(url=self.url, data=_data, headers=self.headers, cookies=self.cookies).json()
            if res["errorCode"] == 0:
                return res
            else:
                print("翻译失败")
                return None
        except Exception as e:
            print(f"请求翻译失败！！")
            return None

    def main(self):
        pass


if __name__ == '__main__':
    print(YD().spider("你好"))

